package com.jjx.trainingapi.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.jjx.trainingapi.common.ErrorCode;
import com.jjx.trainingapi.common.RT;
import com.jjx.trainingapi.entity.param.GetUserIconParam;
import com.jjx.trainingapi.entity.po.DcUser;
import com.jjx.trainingapi.entity.vo.LoginVo;
import com.jjx.trainingapi.entity.vo.UserInfoVo;
import com.jjx.trainingapi.service.DcUserService;
import com.jjx.trainingapi.util.LoginManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author LoveHuahua
 * @date 2022年05月24日 9:11
 * @description believe in yourself
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    DcUserService userService;


    @PostMapping("/getUserInfo")
    @SaCheckLogin
    public RT<UserInfoVo> getUserInfo() {
        return RT.ok(userService.getUserInfo(LoginManager.getUserId()));
    }

    /**
     * 获取用户头像
     * @param param
     * @return
     */
    @PostMapping("/getUserIcon")
    public RT<String> getUserIcon(@RequestBody GetUserIconParam param) {
        DcUser dcUser = userService.lambdaQuery().eq(DcUser::getUsername, param.getUserName()).one();
        return RT.ok(dcUser == null ? "" :dcUser.getAvatarUrl());
    }

    /**
     * 登录接口
     *
     * @return
     */
    @PostMapping("/login")
    public Object login(@RequestBody DcUser user) {
        DcUser one = userService.lambdaQuery().eq(DcUser::getUsername, user.getUsername()).eq(DcUser::getPassword, user.getPassword()).one();
        if (one != null) {
            StpUtil.login(one.getId());
            String tokenValue = StpUtil.getTokenValue();
            LoginVo loginVo = new LoginVo();
            BeanUtils.copyProperties(one, loginVo);
            loginVo.setToken(tokenValue);
            return RT.ok(loginVo);
        }
        return RT.error(ErrorCode.USER_PASSWORD_ERROR);
    }


    /**
     * 注册接口
     *
     * @return
     */
    @PostMapping("/register")
    public Object register(@RequestBody DcUser user) {
        //注册
        userService.register(user);
        StpUtil.login(user.getId());
        String tokenValue = StpUtil.getTokenValue();
        LoginVo loginVo = new LoginVo();
        BeanUtils.copyProperties(user, loginVo);
        loginVo.setToken(tokenValue);
        return RT.ok(loginVo);
    }

    @PostMapping("/updateUserInfo")
    @SaCheckLogin
    public Object updateUserInfo(@RequestBody DcUser user) {
        user.setId(LoginManager.getUserId());
        userService.updateById(user);
        return RT.ok("");
    }

}
